package gwtI18nEditor.filetools;

import gwtI18nEditor.datamodel.Directory;
import gwtI18nEditor.datamodel.Locale;
import gwtI18nEditor.datamodel.MessageFile;
import gwtI18nEditor.datamodel.TranslationEntry;
import gwtI18nEditor.datamodel.TranslationFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProjectParser {

	public static int parseDirectory(File fileDirectory, Directory dataDirectory) {
		List<MessageFile> msgFiles = new ArrayList<MessageFile>();
		Map<String, List<TranslationFile>> xlnFiles = 
				new HashMap<String, List<TranslationFile>>();
		int result = 0;
		String[] children = fileDirectory.list();
		if (children!=null) {
			for (String child: children) {
				File childFile = new File(fileDirectory, child);
				if (childFile.isDirectory()) {
					result += parseDirectory(childFile, dataDirectory.addSubdirectory(childFile, child));
				} else {
					String lowerChild = child.toLowerCase();
					if (lowerChild.endsWith(".java")) {
						MessageFile msgFile = JavaFileParser.parseFile(dataDirectory, childFile);
						if (msgFile!=null) msgFiles.add(msgFile);
					} else if (lowerChild.endsWith(".properties")) {
						TranslationFile xlnFile = PropertiesFileParser.parseFile(childFile);
						if (xlnFile!=null) {
							List<TranslationFile> translations = xlnFiles.get(xlnFile.getIdentifier());
							if (translations==null) {
								translations = new ArrayList<TranslationFile>();
								xlnFiles.put(xlnFile.getIdentifier(), translations);
							}
							translations.add(xlnFile);
						}
					}
				}
			}
			for (MessageFile msgFile: msgFiles) {
				dataDirectory.addFile(msgFile);
				System.out.println("  - "+msgFile.getPackage()+"."+msgFile.getIdentifier()+":");
				List<TranslationFile> translations = xlnFiles.get(msgFile.getIdentifier());
				if (translations!=null) {
					System.out.print("      - Translations: ");
					boolean first = true;
					for (TranslationFile xlnFile: translations) {
						String language = xlnFile.getLanguage();
						Locale locale = (language==null) ? null : new Locale(xlnFile.getLanguage(), xlnFile.getCountry());
						if (first) first = false; else System.out.print(", ");
						System.out.print(((locale==null) ? "default" : locale.getDescription()));
						for (TranslationEntry translation : xlnFile.getEntries()) {
							msgFile.addTranslation(translation.getIdentification(), locale, translation.getContent());
						}
					}
					if (first) System.out.println("none"); else System.out.println();
				}
				result++;
				System.out.println("      - Message count: "+msgFile.msgCount());
			}
		}
		return result;
	}	
}
